//本地数据保存/读取封装,

import {IS_FOR_WX} from "./AppConfig";

function getKey(key) {
  return key;
}

/**
 * 保存数据
 * @param key
 * @param value
 */
function setItem(key, value) {
  key = getKey(key);
  let toSave = JSON.stringify(value);
  if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
    wx.setStorage({
      key,
      data: toSave
    })
  } else {
    cc.sys.localStorage.setItem(key, toSave);
  }
}

/**
 * 取数据
 * @param key
 * @param defaultValue
 */
function getItem(key, defaultValue) {
  key = getKey(key);
  let storageData;
  if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
    storageData = wx.getStorageSync(key);
  } else {
    storageData = cc.sys.localStorage.getItem(key);
  }
  
  if (storageData === null || storageData === '' || storageData === undefined) {
    storageData = defaultValue;
  } else {
    storageData = JSON.parse(storageData);
  }
  return storageData;
}

/**
 * 移除数据
 * @param key
 */
function removeItem(key) {
  key = getKey(key);
  cc.sys.localStorage.removeItem(key);
}


let LocalData = {
  setItem,
  getItem,
  removeItem
};
// module.exports = LocalData;
//全局变量
window.LocalData = window.LocalData || LocalData;

